package com.jzo2o.health.handleException;


import com.jzo2o.health.model.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.List;
import java.util.StringJoiner;

/**
 * @author mwdr
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("未知异常：{}", e.getClass().getName());
        log.error(e.getMessage());
        return Result.setInfo(e.getMessage());
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        String msg = e.getMessage();
        String[] split = msg.split("'");
        log.error("{}：{}已存在！！", e.getClass().getName(),split[1]);
        return Result.setInfo(split[1] + "已存在！！");
    }

    @ExceptionHandler
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringJoiner str = new StringJoiner(",");
        for (FieldError fieldError : fieldErrors) {
            str.add(fieldError.getDefaultMessage());
        }
        log.info("数据校验异常，异常信息为：{}",str);
        return Result.setInfo(str.toString());
    }

    @ExceptionHandler
    public Result handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e){
        log.info("方法参数不匹配，{}",e.getMessage());
        return Result.setInfo("请检查信息是否填写正确！！");
    }

}
